import { Model as CommonModel, Op } from 'sequelize';

export class Model extends CommonModel {
  static async chunk(options, callback, chunkSize = 20) {
    const primaryKey = this.PRIMARY_KEY || 'id';

    // 默认按 id 升序排序，类似 Laravel
    const defaultOrder = [[primaryKey, 'ASC']];
    const { where = {}, order = defaultOrder, limit = chunkSize } = options;

    let lastId = null;
    let processedCount = 0;

    try {
      while (true) {
        // 构造查询条件
        const query = {
          where: {
            ...where,
            ...(lastId ? { [primaryKey]: { [Op.gt]: lastId } } : {}), // 从上次的 lastId 开始
          },
          order,
          limit,
        };

        // 查询一批数据
        const chunkData = await this.findAll(query);

        // 如果没有数据，退出循环
        if (chunkData.length === 0) {
          break;
        }

        // 执行回调处理当前块
        await callback(chunkData);

        // 更新 processedCount 和 lastId
        processedCount += chunkData.length;
        lastId = chunkData[chunkData.length - 1][primaryKey]; // 取最后一条记录的 id

        // 如果返回的数据少于 limit，说明已到末尾
        if (chunkData.length < limit) {
          break;
        }
      }
    } catch (error) {
      throw new Error(`Chunk processing failed: ${error.message}`);
    }

    return processedCount; // 返回总处理条数
  }
}